IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SaveSrvrInstncEAV' AND type = 'P')
     DROP PROCEDURE dbo.SaveSrvrInstncEAV
GO

CREATE PROCEDURE dbo.SaveSrvrInstncEAV
     @SrvrInstncId             int,
     @ParameterId              int,
     @ParameterMultiId         int = 0,
     @ParameterValue           varchar(8000),
     @InsertOnlyFlag           tinyint = 0
AS
/*
 *
 * SaveSrvrInstncEAV
 *
 * Purpose:      
 *
 * Inputs:       
 *
 * Assumes:      
 *
 * Effects:      
 *
 * Returns:      
 *
 * Note(s):      
 *
 * CfgCtrl Keys: None
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 11/09/2011, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     DECLARE @NOW      datetime,
             @DefValue varchar(8000)

     -- Get current date/time
     SELECT @NOW = CURRENT_TIMESTAMP 

     -- Get default value
     SELECT @DefValue = ParameterDefaultValue
     FROM   dbo.Parameter
     WHERE  ParameterId = @ParameterId

     -- Find out if we have the record already
     IF NOT EXISTS ( SELECT 'X'
                     FROM   dbo.SrvrInstncEAV
                     WHERE  SrvrInstncId     = @SrvrInstncId
                     AND    ParameterId      = @ParameterId
                     AND    ParameterMultiId = @ParameterMultiId )
     BEGIN -- We do not have this record, so we will do an insert
          INSERT dbo.SrvrInstncEAV
               ( SrvrInstncId,
                 ParameterId,
                 ParameterMultiId,
                 ParameterValue,
                 LastModDt )
          SELECT @SrvrInstncId,
                 @ParameterId,
                 @ParameterMultiId,
                 @ParameterValue,
                 @NOW
     END -- End New insert
     ELSE
     BEGIN -- We have the record so we do an insert if there is a difference. If we are allowed
          IF ( @InsertOnlyFlag = 0 )
          BEGIN
               UPDATE dbo.SrvrInstncEAV
               SET    ParameterValue   = @ParameterValue,
                      LastModDt        = @NOW
               WHERE  SrvrInstncId     = @SrvrInstncId
               AND    ParameterId      = @ParameterId
               AND    ParameterMultiId = @ParameterMultiId
               AND  ( ParameterValue != @ParameterValue
                   OR ParameterValue IS     NULL AND @ParameterValue IS NOT NULL
                   OR ParameterValue IS NOT NULL AND @ParameterValue IS     NULL )
               -- LastModDt is not compared as it is only metadata and not data proper.
          END
     END
END
GO
